package com.suray.system.run.util;

import java.util.*;

public class PortTaskContainer {

    private List<TaskNumContainer> containers;

    public PortTaskContainer() {
        containers = new ArrayList<>();
    }

    public void addTask(String portCode, int layer) {
        for (TaskNumContainer taskNumContainer : containers) {
            if (taskNumContainer.portCode.equals(portCode)) {
                taskNumContainer.addTask(layer);
                return;
            }
        }

        TaskNumContainer container = new TaskNumContainer(portCode);
        int index = containers.indexOf(container);
        if (index == -1) {
            container.addTask(layer);
            containers.add(container);
        } else {
            containers.get(index).addTask(layer);
        }
    }

    public int getTaskNum(String portCode, int layer) {
        TaskNumContainer container = new TaskNumContainer(portCode);
        int index = containers.indexOf(container);
        if (index == -1) {
            return 0;
        }

        Integer taskNum = containers.get(index).getTaskNum(layer);
        return taskNum == null ? 0 : taskNum;
    }

    class TaskNumContainer {
        private String portCode;

        private Map<Integer, Integer> layerTask;

        public TaskNumContainer(String portCode) {
            this.portCode = portCode;
            layerTask = new HashMap<>();
        }

        public void addTask(int layer) {
            Integer taskNum = layerTask.get(layer);
            if (taskNum == null) {
                layerTask.put(layer, 1);
            } else {
                layerTask.put(layer, taskNum + 1);
            }
        }

        public Integer getTaskNum(int layer) {
            return layerTask.get(layer);
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;
            TaskNumContainer container = (TaskNumContainer) o;
            return Objects.equals(portCode, container.portCode);
        }

        @Override
        public int hashCode() {
            return Objects.hash(portCode, layerTask);
        }
    }
}
